<?php

/**
 * @abstract ihome Passport
 * @author Dai Shaowei <daishaowei@sohu-inc.com>
 * @date 2010-03-11
 * @version 0.1
 * @desc 爱家会员登录成功后，有两个Cookie：Sohu Passport的相关Cookie，爱家会员的Cookie，
 * @Last-modified 2010-3-29
 */

class IhomePassport {

    /**
     * @array sohu Passport信息，包括'userid', 'username','domain'
     */
    private $_sohuPassportInfo = null;

    /**
     * @array 焦点Passport对象
     */
    private $_focusPassport = null;

   /**
     * @object DB Object: User
     */
    private $_act_user = null;

    /**
     * @array ihome Passport信息，包括'id', 'verified'
     */
    private $_ihomePassportInfo = null;

    /**
     * @bool 设置是否处于调试状态
     */
    private $_debug = false;

    /**
     * @string ihome cookie名
     */
    const IHOME_COOKIE_NAME = 'passport_ihome';

    /**
     * @string ihome cookie名
     */
    const IHOME_DOMAIN_NAME = 'ihome.sohu.com';
    

    /**
     * 构造函数
     */
    public function __construct() {
     	//$this->_act_user = new Model_User();   
    }

    /**
     * @return array 返回Sohu Passport信息
     * $info['userid'] Sohu Passport的userid，如test@focus.cn，注意不要和爱家会员ID混淆
     * $info['username'] Sohu Passport的username，为userid的前半部分，test
     * $info['domain'] Sohu Passport的域，如focus.cn
     *
     */
    public function getSohuPassportInfo() {
        return $this->_sohuPassportInfo;
    }

    /**
     *  @return array 返回Ihome Passport信息
     *  $info['id'] 会员ID
     *  $info['user_from'] 会员类型，0表示线上，1表示线下
     *  $info['verified'] 线下会员是否已激活，0未激活，1已激活
     *
     */
    public function getIhomePassportInfo() {
        return $this->_ihomePassportInfo;
    }

    /**
     * 设置是否处于调试状态
     *
     */
    public function setDebug($debug) {
        $this->_debug = $debug;
    }

    /**
     * 设置是否处于调试状态
     *
     */
    private function debug() {
        if (!$this->_debug) return;
        $this->_ihomePassportInfo = array(
            'id'       => 1,
            'user_from'     => 0,
            'verified' => 1
        );
    }

    /**
     * 设置Sohu通行证信息，写入数组 $this->_sohuPassportInfo
     * 注意：是从Apache Header取的信息
     *
     * @return array $passport['userid'], 'username', 'domain'
     */
    public function setSohuPassportInfo() {
        $this->_focusPassport = new ComFocusPassport();
        $this->_sohuPassportInfo = $this->_focusPassport->getSohuPassportInfo();
        return $this->_sohuPassportInfo;
    }

    /**
     * 核心函数：解析Sohu Passport, Ihome Passport，
     * not only check, but also check in DB, set cookie
     *
     * @return int passport的状态
     * 0表示未登录Sohu Passport，
     * 1表示已登录Sohu Passport，但还不是爱家会员，
     * 2表示已登录Sohu Passport，是爱家会员
     */
    public function decrypt() {
        $this->setSohuPassportInfo();

	$this->parseIhomeUnverifyCookie();
	if ($this->isMember())
		return;

    	// 解析ihome cookie
    	$this->parseIhomeCookie();
    	if ($this->isMember()) { // 有ihome cookie，且不为空
    		$verified = $this->_ihomePassportInfo['verified'];
    		if ($verified) { // 已激活
    			if (empty($this->_sohuPassportInfo) || $this->_sohuPassportInfo['userid'] != $this->_ihomePassportInfo['login_name']) {
    				$this->unsetIhomeCookie(); // 已激活用户，必须登录Sohu Passport，且必须一致
    				return;
    			}
    			return; // 有ihome cookie, sohu cookie,且已激活
    		}
    		return;
    	}
    	
    	// 以下为没有ihome cookie的情况，且未登录Sohu Passport的情况
        if (empty($this->_sohuPassportInfo)) {
            return;
        }
    
        // 以下为没有ihome cookie，但登录为Sohu Passport的情况

        // 数据库中查找是否为爱家会员，同时设置$this->_ihomePassportInfo
        $this->setIhomePassportInfo();
        
        $this->debug(); // 测试状态下，手动设定_ihomePassportInfo
        if ($this->isMember()) {
        	$this->setIhomeCookie(); //登录Sohu Passport，是爱家会员，没有Cookie的，设置Cookie
        }
        return;
    }

    /**
     * 从数据库获取会员的唯一id等信息，放入$this->_ihomePassportInfo
	 * @modify by masonsu 2010-3-22
     * @return bool 
     */
    public function setIhomePassportInfo() {
		/*
        // 从数据库中获取其id, verified等字段
        $data = $this->_act_user->getUserInfoByPassport($this->_sohuPassportInfo['userid']);

        // 数据库中不存在，表示不是爱家会员
        if (empty($data)) {
            $this->setNonmemberInfo();
            return;
        }

		//设置verified的状态，采用新的userflag标识.
		$is_verified = $this->_act_user->hasVerifiedByPassport($this->_sohuPassportInfo['userid'],$data);
        // 以后ihome passport信息都从此数组中取
        $this->_ihomePassportInfo = array(
            'id'         => $data['id'],
            'user_from'  => $data['user_from'],
            'verified'   => intval($is_verified),
			'login_name' => $data['login_name'],
			'realname'   => $data['realname'],
			'card'       => $data['card'],
			'rank'       => $data['rank'],
			'service'    => $data['service'],
			'message'    => $data['message'],
        	'mobile'     => $data['mobile'],
		'nickname'   => $data['nickname'],
        );
        return;
		*/
    }
	
	/**
     * 获取系统返回的vip申请信息
     *
     * @return string 返回信息
	 * @author masonsu 2010-3-22
     */
	 public function getMessage() {
        if(!empty($this->_ihomePassportInfo['message']))
			return $this->_ihomePassportInfo['message'];
		return '';
    }
    
    /**
     * 是否已经登录为爱家会员
     *
     * @return bool true表示已登录，false表示未登录
     */
    public function isMember() {
        return $this->_ihomePassportInfo && $this->_ihomePassportInfo['id'] > 0;
    }

    // 功能同上
    public function isLogin() {
        return $this->_ihomePassportInfo && $this->_ihomePassportInfo['id'] > 0;
    }
    
    /**
     * 是否是管理员，用于前台的留言等操作
     *
     * @return bool true表示已登录，false表示未登录
     */
    public function isAdmin() {
        return $this->_ihomePassportInfo && $this->_ihomePassportInfo['id'] > 0 && $this->_ihomePassportInfo['rank'] == 99;
    }
    /**
     * 是否存在ihome cookie
     */
    public function hasIhomeCookie() {
        return !empty($_COOKIE[self::IHOME_COOKIE_NAME]);
    }

    /**
     * set ihome cookie
     *
     * @param array $ihomePassportInfo 用户的ihome登录信息
	 * @modify by masonsu 2010-3-22
     * @return
     */
    public function setIhomeCookie($ihomePassportInfo = array()) {
        if (!empty($ihomePassportInfo)) {
            $this->_ihomePassportInfo = $ihomePassportInfo;
        }
        $info = $this->_ihomePassportInfo;
        $cookie_value = $info['id'] . "|" . $info['user_from'] . "|" . $info['verified'] . '|' . $info['login_name'] . '|' . $info['realname'] . '|' . $info['card'] . '|' . $info['rank'] . '|' . $info['service'] . '|' . $info['mobile'] . '|' . $info['nickname'];
        
        // Cookie 加密，采用焦点现有加密方式
        $encrypt_cookie = $this->_focusPassport->focusCookieEncrypt($cookie_value);
        $expire = time() + 3600 * 24 * 365; // 保留一年
        setcookie(self::IHOME_COOKIE_NAME, $encrypt_cookie, $expire, "/", self::IHOME_DOMAIN_NAME, 0);
    }

    /**
     * set unverified user cookie
     *
     * @param array $ihomePassportInfo 用户的ihome登录信息
	 * @modify by masonsu 2010-3-22
     * @return
     */
    public function setUnverifyUserCookie($ihomePassportInfo = array()) {
        if (!empty($ihomePassportInfo)) {
            $this->_ihomePassportInfo = $ihomePassportInfo;
        }
        $info = $this->_ihomePassportInfo;
        $cookie_value = $info['id'] . "|" . $info['user_from'] . "|" . $info['verified'] . '|' . $info['login_name'] . '|' . $info['realname'] . '|' . $info['card'] . '|' . $info['rank'] . '|' . $info['service'] . '|' . $info['mobile'] . '|' . $info['nickname'];
        
        // Cookie 加密，采用焦点现有加密方式
	if (empty($this->_focusPassport))
		$this->_focusPassport = new ComFocusPassport();
        $encrypt_cookie = $this->_focusPassport->focusCookieEncrypt($cookie_value);
        $expire = time() + 3600 * 24 * 365; // 保留一年
        //setcookie(constant('_CONFIG_USER_UNVERIFY_'), $encrypt_cookie, $expire, "/", self::IHOME_DOMAIN_NAME, 0);
        setcookie(Kohana::config('passport.cookie.user_unverify'), $encrypt_cookie, $expire, "/", 'shangcheng.sohu.com', 0);//, self::IHOME_DOMAIN_NAME, 0);
	//setcookie("testtest", "sssss", $expire, "/");
        //echo "setcookie(".constant('_CONFIG_USER_UNVERIFY_').", $encrypt_cookie, $expire, \"/\", ".self::IHOME_DOMAIN_NAME.", 0);\n";
    }

    
    public function setNonmemberInfo() {
    	$this->_ihomePassportInfo = array(
            'id'         => 0,
            'user_from'  => 0,
            'verified'   => 0,
            'login_name' => 0,
            'realname'   => 0,
            'card'       => 0,
            'rank'       => 0,
            'service'    => 0,
            'message'    => 0,
    		'mobile'     => 0,
		'nickname'   => 0,
    	);
    }

    /**
     * unset ihome cookie
     */
    public function unsetIhomeCookie() {
        setcookie(self::IHOME_COOKIE_NAME, null, null, "/", self::IHOME_DOMAIN_NAME, 0);
	$this->unsetVerifyUserCookie();
    }

    public function unsetVerifyUserCookie() {
        setcookie(Kohana::config('passport.cookie.user_unverify'), null, null, "/");//, self::IHOME_DOMAIN_NAME, 0);
		//setcookie('tuan_unverify', '', time() - 3600, '/', 'tuan.sohu.com');
    }

    /**
     * set ihome cookie
     *
     * @param string $cookie cookie值
	 * @modify by masonsu 2010-3-22
     * @return
     */
    public function parseIhomeCookie() {


        $encrypt_cookie = isset($_COOKIE[self::IHOME_COOKIE_NAME]) ? $_COOKIE[self::IHOME_COOKIE_NAME] : NULL;
        if (empty($encrypt_cookie)) {
        	$this->setNonmemberInfo();
            return;
        }
        $cookie = $this->_focusPassport->focusCookieDecrypt($encrypt_cookie);
        $arr = explode("|", $cookie);
        $this->_ihomePassportInfo = array(
            'id'         => $arr[0],
            'user_from'  => $arr[1],
            'verified'   => $arr[2],
			'login_name' => $arr[3],
			'realname'   => $arr[4],
			'card'       => $arr[5],
			'rank'       => $arr[6],
			'service'    => $arr[7],
        	'mobile'     => $arr[8],
		'nickname'   => $arr[9],
        );
    }

    /**
     * 解析未激活用户的cookie
     * @return: void
     * @author: xiaoliangyang
     */
    public function parseIhomeUnverifyCookie() {

		$cookie_name  = Kohana::config('user.cookie.unverify');
        $encrypt_cookie = isset($_COOKIE[$cookie_name]) ? $_COOKIE[$cookie_name] : NULL;
        if (empty($encrypt_cookie)) {
            return;
        }

	$this->_ihomePassportInfo = array();
        $cookie = $this->_focusPassport->focusCookieDecrypt($encrypt_cookie);
        $arr = explode("|", $cookie);
        $this->_ihomePassportInfo = array(
            'id'         => $arr[0],
            'user_from'  => $arr[1],
            'verified'   => $arr[2],
			'login_name' => $arr[3],
			'realname'   => $arr[4],
			'card'       => $arr[5],
			'rank'       => $arr[6],
			'service'    => $arr[7],
        	'mobile'     => $arr[8],
		'nickname'   => $arr[9],
        );
    }


    /**
     * 是否已经为验证会员
     * 验证会员：线上会员，或者线下已激流会员
     *
     * @return bool true表示是验证会员，false表示不是验证会员
     */
    public function hasVerified() {
        if (!$this->isMember()) return false;
        return $this->_ihomePassportInfo['verified'] == 1;
    }

    /**
     * 用户激活后，修改Cookie
     */
    public function setVerified($update) {
    	if (is_array($update)) {
	        $this->_ihomePassportInfo['verified'] = $update['verified'];
	        $this->_ihomePassportInfo['login_name'] = $update['login_name'];
    	}
        
        // 重新设置 Ihome Cookie
        $this->setIhomeCookie();
    }
}
